import 'package:flutter/material.dart';
import 'package:native_video_cache/native_video_cache.dart';
import 'video_player/video_player_controller.dart';
import 'video_player/video_player_widget.dart';
import 'utils/error_handler.dart';

class VideoPlayerDemo extends StatefulWidget {
  final String videoUrl;
  final String title;

  const VideoPlayerDemo({
    super.key,
    required this.videoUrl,
    required this.title,
  });

  @override
  State<VideoPlayerDemo> createState() => _VideoPlayerDemoState();
}

class _VideoPlayerDemoState extends State<VideoPlayerDemo> {
  late NativeAvPlayerController _controller;
  bool _isInitialized = false;
  bool _isManagerInitialized = false;
  String _status = '正在初始化缓存管理器...';

  // 缓存状态
  double _cacheProgress = 0.0;
  CacheStatus _cacheStatus = CacheStatus.none;

  // 错误信息
  VideoErrorInfo? _currentErrorInfo;

  @override
  void initState() {
    super.initState();
    _initializeNativeVideoCacheManager();
  }

  @override
  void dispose() {
    if (_isInitialized) {
      _controller.dispose();
    }
    super.dispose();
  }

  Future<void> _initializeNativeVideoCacheManager() async {
    try {
      setState(() {
        _status = '正在初始化缓存管理器...';
      });

      // 先初始化 NativeVideoCacheManager
      await NativeVideoCacheManager.initialize(
        CacheConfig(
          maxCacheSize: 500 * 1024 * 1024, // 500MB
          maxConcurrentDownloads: 2,
          connectTimeout: 30000,
          readTimeout: 30000,
        ),
      );

      setState(() {
        _isManagerInitialized = true;
        _status = '缓存管理器初始化成功，正在初始化播放器...';
      });

      // 然后初始化播放器
      await _initializePlayer();
    } catch (e) {
      setState(() {
        _status = '缓存管理器初始化失败: $e';
      });
    }
  }

  Future<void> _initializePlayer() async {
    if (!_isManagerInitialized) {
      setState(() {
        _status = '缓存管理器未初始化';
      });
      return;
    }

    _controller = NativeAvPlayerController();

    // 设置事件监听器
    _controller.onStateChanged = (state) {
      if (mounted) {
        setState(() {
          _status = _getStatusText(state);
          // 如果状态变为error，获取错误信息
          if (state == NativeAvPlayerState.error) {
            _currentErrorInfo = _controller.currentErrorInfo;
          } else {
            _currentErrorInfo = null;
          }
        });
      }
    };

    _controller.onError = (error) {
      debugPrint('播放器 onError: $error');
      if (mounted) {
        setState(() {
          _currentErrorInfo = _controller.currentErrorInfo;
        });

        // 如果有详细的错误信息，显示友好的错误提示，否则显示简单提示
        final errorMessage = _currentErrorInfo?.title ?? '播放错误: $error';
        ScaffoldMessenger.of(context)
          ..hideCurrentSnackBar()
          ..showSnackBar(
            SnackBar(
              content: Text(errorMessage),
              backgroundColor: Colors.red,
            ),
          );
      }
    };

    _controller.onProgressChanged = (position, duration) {
      // 可以在这里处理进度更新
    };

    // 缓存事件监听
    _controller.onCacheProgressChanged = (progress) {
      debugPrint('onCacheProgressChanged: $progress');
      if (mounted) {
        setState(() {
          _cacheProgress = progress;
        });
      }
    };

    _controller.onCacheStatusChanged = (status) {
      debugPrint('onCacheStatusChanged: $status');
      if (mounted) {
        setState(() {
          _cacheStatus = status;
        });
      }
    };

    try {
      await _controller.initialize(
        widget.videoUrl,
        autoPlay: true,
        allowFullScreen: true,
        showControls: true, // 使用chewie内置控制层
      );

      setState(() {
        _isInitialized = true;
        _status = '播放器初始化成功';
        _currentErrorInfo = null;
      });
    } catch (e) {
      // 使用智能错误分析器分析初始化错误
      try {
        final errorInfo = await VideoErrorHandler.analyzeError(
          e.toString(),
          widget.videoUrl,
        );
        setState(() {
          _currentErrorInfo = errorInfo;
          _status = errorInfo.title;
        });
      } catch (analysisError) {
        // 如果错误分析失败，使用默认错误信息
        setState(() {
          _status = '播放器初始化失败: $e';
          _currentErrorInfo = null;
        });
      }
    }
  }

  String _getStatusText(NativeAvPlayerState state) {
    switch (state) {
      case NativeAvPlayerState.idle:
        return '空闲';
      case NativeAvPlayerState.loading:
        return '加载中...';
      case NativeAvPlayerState.ready:
        return '准备就绪';
      case NativeAvPlayerState.playing:
        return '播放中';
      case NativeAvPlayerState.paused:
        return '已暂停';
      case NativeAvPlayerState.buffering:
        return '缓冲中...';
      case NativeAvPlayerState.error:
        return '播放错误';
      case NativeAvPlayerState.disposed:
        return '已释放';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 播放器容器
          AspectRatio(
            aspectRatio: 16 / 9,
            child: Container(
              color: Colors.black,
              child: _isInitialized
                  ? NativeAvPlayerWidget(
                      controller: _controller,
                      showDefaultControls: false, // 不使用我们的默认控制层
                      // chewie 内置控制层已经在 ChewieController 中启用
                    )
                  : _buildLoadingOrErrorWidget(),
            ),
          ),

          // 播放器信息和控制面板
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(16),
              color: Colors.grey[900],
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 视频信息
                    Text(
                      widget.title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      widget.videoUrl,
                      style: const TextStyle(
                        color: Colors.white70,
                        fontSize: 12,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 16),

                    // 状态信息
                    Card(
                      color: Colors.grey[800],
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '播放器状态',
                              style: const TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            if (_isInitialized) ...[
                              _buildStatusRow('状态', _status),
                              _buildStatusRow(
                                  '是否播放', _controller.isPlaying ? '是' : '否'),
                              _buildStatusRow(
                                  '是否缓冲', _controller.isBuffering ? '是' : '否'),
                              _buildStatusRow('当前位置',
                                  _formatDuration(_controller.position)),
                              _buildStatusRow(
                                  '总时长', _formatDuration(_controller.duration)),
                              _buildStatusRow('宽高比',
                                  _controller.aspectRatio.toStringAsFixed(2)),
                              _buildStatusRow(
                                  '代理URL', _controller.proxyUrl ?? '无'),
                              const Divider(color: Colors.white54),
                              _buildStatusRow(
                                  '缓存状态', _getCacheStatusText(_cacheStatus)),
                              _buildStatusRow('缓存进度',
                                  '${(_cacheProgress * 100).toStringAsFixed(1)}%'),
                              if (_cacheProgress > 0)
                                Padding(
                                  padding:
                                      const EdgeInsets.symmetric(vertical: 4),
                                  child: LinearProgressIndicator(
                                    value: _cacheProgress,
                                    backgroundColor: Colors.white24,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      _cacheStatus == CacheStatus.cached
                                          ? Colors.green
                                          : Colors.blue,
                                    ),
                                  ),
                                ),
                            ] else
                              Text(
                                _status,
                                style: const TextStyle(color: Colors.white70),
                              ),
                          ],
                        ),
                      ),
                    ),

                    const SizedBox(height: 16),

                    // 控制按钮
                    if (_isInitialized) ...[
                      const Text(
                        '快捷控制',
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Wrap(
                        spacing: 8,
                        children: [
                          ElevatedButton(
                            onPressed: _controller.play,
                            child: const Text('播放'),
                          ),
                          ElevatedButton(
                            onPressed: _controller.pause,
                            child: const Text('暂停'),
                          ),
                          ElevatedButton(
                            onPressed: _controller.stop,
                            child: const Text('停止'),
                          ),
                          ElevatedButton(
                            onPressed: () => _controller.setPlaybackSpeed(0.5),
                            child: const Text('0.5x'),
                          ),
                          ElevatedButton(
                            onPressed: () => _controller.setPlaybackSpeed(1.0),
                            child: const Text('1.0x'),
                          ),
                          ElevatedButton(
                            onPressed: () => _controller.setPlaybackSpeed(2.0),
                            child: const Text('2.0x'),
                          ),
                          ElevatedButton(
                            onPressed: _controller.toggleFullScreen,
                            child: const Text('全屏'),
                          ),
                          ElevatedButton(
                            onPressed: _testCache,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue,
                            ),
                            child: const Text('测试缓存'),
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建加载或错误显示Widget
  Widget _buildLoadingOrErrorWidget() {
    // 如果有详细的错误信息，显示友好的错误界面
    if (_currentErrorInfo != null) {
      final errorInfo = _currentErrorInfo!;

      return Container(
        color: Colors.black,
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 错误图标
              Text(
                errorInfo.icon,
                style: const TextStyle(fontSize: 48),
              ),
              const SizedBox(height: 16),

              // 错误标题
              Text(
                errorInfo.title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),

              // 错误描述
              Text(
                errorInfo.message,
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),

              // 解决建议
              if (errorInfo.suggestions.isNotEmpty) ...[
                const Text(
                  '解决建议:',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                ...errorInfo.suggestions.take(3).map(
                      // 只显示前3个建议
                      (suggestion) => Padding(
                        padding: const EdgeInsets.symmetric(vertical: 2),
                        child: Row(
                          children: [
                            const Text(
                              '• ',
                              style: TextStyle(color: Colors.white70),
                            ),
                            Expanded(
                              child: Text(
                                suggestion,
                                style: const TextStyle(
                                  color: Colors.white70,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                const SizedBox(height: 16),
              ],

              // 重试按钮
              if (errorInfo.canRetry)
                ElevatedButton.icon(
                  onPressed: () {
                    // 重新初始化播放器
                    _initializePlayer();
                  },
                  icon: const Icon(Icons.refresh),
                  label: const Text('重试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                  ),
                ),
            ],
          ),
        ),
      );
    }

    // 默认的加载界面
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
          const SizedBox(height: 16),
          Text(
            _status,
            style: const TextStyle(color: Colors.white),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildStatusRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(color: Colors.white70, fontSize: 12),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(color: Colors.white, fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '$hours:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '$minutes:${twoDigits(seconds)}';
    }
  }

  String _getCacheStatusText(CacheStatus status) {
    switch (status) {
      case CacheStatus.none:
        return '未缓存';
      case CacheStatus.caching:
        return '缓存中';
      case CacheStatus.cached:
        return '已缓存';
      case CacheStatus.error:
        return '缓存错误';
    }
  }

  Future<void> _testCache() async {
    try {
      // 强制开始缓存当前视频
      await NativeVideoCacheManager.startCache(widget.videoUrl);

      // 显示测试结果
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('缓存测试已启动，请观察缓存状态和进度变化'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('缓存测试失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }
}
